package com.vooda.config;

import com.vooda.dto.vo.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.List;

/**
 * 表单校验切面
 * <p>校验需要验证表单的接口，如果校验不通过，返回表单字段校验不通过的原因</p>
 *
 * @author charlee
 * @date 2017年11月30日
 */
@Order(2)
@Slf4j
@Aspect
@Component
public class BindingResultAop {

    @Pointcut("execution(* com.vooda.controller.*Controller.*(..))")
    public void controllerPointcut() {
    }

    @Around(value = "controllerPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        BindingResult bindingResult = null;
        for (Object arg : joinPoint.getArgs()) {
            if (arg instanceof BindingResult) {
                bindingResult = (BindingResult) arg;
                break;
            }
        }

        if (bindingResult != null) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            if (!CollectionUtils.isEmpty(errors)) {
                BaseResult baseResult = BaseResult.getParamErrorResult();
                List<String> msg = new ArrayList<>();
                for (FieldError error : errors) {
                    msg.add(error.getField() + " : " + error.getDefaultMessage());
                }
                baseResult.setErrors(msg);
                return baseResult;
            }
        }
        return joinPoint.proceed();
    }
}
